/*
 * easysmtp - A simple C lib in Linux to help you send mails in an easy way
 * Copyright (C) 2012-2013, easysmtp developers and contributors
 *
 * easysmtp is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * easysmtp is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with easysmtp; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "attach.h"

//如果邮件，构造邮件的发送
int
mail_attachment(SMTP *smtpr, MAIL *mpr) {
	char temp[480] = {0};
	unsigned char b_temp[480] = {0};
	FILE *fp;
	int j, n;
	long int sum = 0;

	for(j = 0; j < mpr->att_len; j++) {
		memset(temp, 0, sizeof(temp));
		sprintf(temp, "--#BOUNDARY2#--\r\n"
				"--#BOUNDARY1#\r\n"
				"Content-Type: application/octet-stream;"
				"name=%s\r\n"
				"Content-Disposion: attachment; " 
				"file_name=%s\r\n"
				"Content-Transfer-Encoding: "
				"base64\r\n\r\n", mpr->file_name_list[j],
						mpr->file_name_list[j]);
		if(SYS_ERROR == send_msg(smtpr, temp)) {
			return SYS_ERROR;
		}
		memset(temp, 0, sizeof(temp));
		memset(b_temp, 0, sizeof(b_temp));
		//打开文件（以二进制方式）
		if((fp = fopen(mpr->file_path_list[j], "rb")) == NULL) {
			return SYS_ERROR;
		}
		while((n = fread(b_temp, sizeof(unsigned char), 480, 
							fp)) != 0) {
			ucto64(b_temp, n);
			sprintf(change, "%s\r\n",change);
			if(SYS_ERROR == send_msg(smtpr,change)) {
				return SYS_ERROR;
			}
			sum += n;
			printf("%ld\n", sum);
		}
	}
	if(SYS_ERROR == send_msg(smtpr,"--#BOUNDARY1#--\r\n")) {
		return SYS_ERROR;
	}
	return SMTP_SUCCESS;
}
